import React, {Component} from 'react';
import {Form, Icon, Input, Button, Checkbox, message} from 'antd';
import fetch from 'isomorphic-fetch';
import {BaseUrl} from '../../common/BaseUrl';
import {hashHistory} from 'react-router-dom';

const FormItem = Form.Item;

class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.register = this.register.bind(this);
        this.showMessage = this.showMessage.bind(this);
        this.handleConfirmPassword = this.handleConfirmPassword.bind(this);
        this.state = {
            passwordHelp: "",
            passwordStatus: ""
        };
    }


    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) {
                console.log('Received values of form: ', values);
                return;
            }
            let userName = values.userName;
            let password = values.password;
            let searchParams = new URLSearchParams();
            searchParams.set('username', userName);
            searchParams.set('password', password);
            let url = BaseUrl + "login";
            fetch(url, {
                method: 'post',
                header: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Access-Control-Allow-Origin': '*',
                },
                body: searchParams,
                credentials: 'include',
                redirect: 'manual',
                mode: 'cors'
            }).then(res => res.json()).then(json => {
                let status = json.code;
                if (status == "success") {
                    /*this.props.history.push("/main/userInfo", null);*/
                } else {
                    this.props.form.setFields({
                        password: {
                            value: "",
                            errors: [new Error('password is error ！please write again')],
                        },
                    });
                    this.props.history.replace("/login", null);
                }
            }).catch(err => {
                console.log(err);
                this.props.history.push("/login", null);
            })
        });
    }


    showMessage(type, message, time) {
        if (type == 'error') {
            message.error(message, time);
        } else {
            message.success(message, time);
        }
    }

    handleConfirmPassword(rule, value, callback) {
        const {getFieldValue} = this.props.form;
        if (value && value !== getFieldValue('password')) {
            callback('两次输入不一致！')
        }
        callback()
    }


    register() {
        /*this.props.history.push("/registerUserInfo", null);*/
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit} className="login-form">
                <FormItem>
                    {getFieldDecorator('userName', {
                        rules: [{required: true, message: 'Please input your username!'}],
                    })(
                        <Input prefix={<Icon type="user" style={{fontSize: 13}}/>}
                               placeholder="Username" id="userName"/>
                    )}
                </FormItem>
                <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{required: true, message: 'Please input your Password!'}],
                    }, {
                        validator: this.handleConfirmPassword
                    })(
                        <Input prefix={<Icon type="lock" style={{fontSize: 13}}/>} type="password"
                               placeholder="Password" id="password"/>
                    )}
                </FormItem>
                <FormItem>
                    {getFieldDecorator('remember', {
                        valuePropName: 'checked',
                        initialValue: true,
                    })(
                        <Checkbox>Remember me</Checkbox>
                    )}
                    <a className="login-form-forgot">Forgot password</a>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        Log in
                    </Button>
                    Or <a onClick={this.props.goRegister}>register now!</a>
                </FormItem>
            </Form>
        );
    }
}

let loginForm = Form.create()(LoginForm);
export default loginForm;